import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatSnackBar, MatSnackBarRef } from '@angular/material/snack-bar';
import {
  MatSnackBarHorizontalPosition,
  MatSnackBarVerticalPosition
} from '@angular/material/snack-bar/snack-bar-config';
import { Router } from '@angular/router';
import { CaptchaService } from '../../../@core/services/captcha.service';

@Component({
  selector: 'SignIn',
  templateUrl: './sign-in.component.html',
  styleUrls: ['../auth.component.scss', './sign-in.component.scss']
})
export class SignInComponent {
  constructor(
    private _snackBar: MatSnackBar,
    private readonly _router: Router,
    private readonly captchaService: CaptchaService
  ) {}

  tabIndex = 1;

  captchaForm = new FormGroup({
    email: new FormControl('', [Validators.required, Validators.email]),
    code: new FormControl('', [
      Validators.required,
      Validators.pattern('^[0-9]{6}$')
    ])
  });

  captchaBtn = '获取';
  captchaBtnDisabled = false;

  getCaptcha = () => {
    const email = this.captchaForm.value.email
    if (!email) {
      return
    }
    this.captchaBtnDisabled = true;
    this.captchaTick();
    // send email captcha
    this.captchaService
      .generateCaptcha(email)
      .subscribe(res => {
        if (res.isSuccess) {
          this.openSnackBar('验证码发送成功');
        }
      });
  };

  captchaTick = () => {
    let tick = 60;
    const interval = setInterval(() => {
      tick -= 1;
      this.captchaBtn = `重试(${tick})`;

      if (tick <= 0) {
        this.captchaBtn = '获取';
        this.captchaBtnDisabled = false;
        clearInterval(interval);
      }
    }, 1000);
  };

  usernameForm = new FormGroup({
    username: new FormControl('', [Validators.required]),
    password: new FormControl('', [
      Validators.required,
      Validators.minLength(6)
    ])
  });

  showPass: boolean = false;
  passInputType = 'password';
  switchShowPass = () => {
    this.showPass = !this.showPass;
    this.passInputType = this.showPass ? 'text' : 'password';
  };

  onSignIn = () => {
    const isValid = (): boolean => {
      if (this.tabIndex === 0) {
        return this.captchaForm.status === 'VALID';
      } else {
        return this.usernameForm.status === 'VALID';
      }
    };

    if (!isValid()) {
      return;
    }
    // todo check user
    this._router.navigate(['/chat']).then(() => {
      return true;
    });
  };

  openSnackBar = (
    message: string,
    action?: string,
    duration = 3000,
    horizontalPosition: MatSnackBarHorizontalPosition = 'center',
    verticalPosition: MatSnackBarVerticalPosition = 'top'
  ): MatSnackBarRef<any> => {
    return this._snackBar.open(message, action, {
      duration,
      horizontalPosition,
      verticalPosition
    });
  };
}
